package com.example.community.list;

import com.example.community.dao.ComtyDao;
import com.example.community.dao.FloorDao;
import com.example.community.dao.RoomDao;
import com.example.community.dao.UnitDao;
import com.example.community.model.Comty;
import com.example.community.model.Floor;
import com.example.community.model.Room;
import com.example.community.model.Unit;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = "/fpfj")
public class FpfjServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String usNo = req.getParameter("usNo");
        req.setAttribute("usNo",usNo);

        List<String[]> addressIsNull = getAddressIsNull();
//        for (String[] strings:addressIsNull){
//            System.out.println(strings[0]);
//            System.out.println(strings[1]);
//        }
        req.setAttribute("address",addressIsNull);

        req.getRequestDispatcher("/WEB-INF/userManager/fpfj.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String usNo = req.getParameter("usNo");
        String fpfj = req.getParameter("fpfj");
        RoomDao roomDao = new RoomDao();
        Room room = roomDao.fandById(Integer.parseInt(fpfj));
        room.setUsNo(Integer.parseInt(usNo));
        Integer update = roomDao.update(room);
        if (update == 1){
            resp.getWriter().write("true");
        }else {
            resp.getWriter().write("false");
        }
    }

    private List<String[]> getAddressIsNull(){
        RoomDao roomDao = new RoomDao();
        List<Room> rooms = roomDao.selectNull();
        List<String[]> list = new ArrayList<>();
        for (Room room:rooms){
            Integer rNo = room.getrNo();
            if (rNo != null){
                Integer unNo = room.getUnNo();
                UnitDao unitDao = new UnitDao();
                Unit unit = unitDao.fandById(unNo);
                Integer fNo = unit.getfNo();
                FloorDao floorDao = new FloorDao();
                Floor floor = floorDao.fandById(fNo);
                Integer ctNo = floor.getCtNo();
                ComtyDao comtyDao = new ComtyDao();
                Comty comty = comtyDao.fandById(ctNo);
                String address = "" + comty.getCtName() + floor.getfName() + unit.getUnName() + room.getrId();
                String[] strings = {address,rNo.toString()};
                list.add(strings);
            }
        }
        return list;

    }
}
